import sys, os
import numpy as np
# sys.path.append(os.getcwd())
from common.config import torqueConfig as Config
from pynverse import inversefunc
import pandas as pd



''' 处理数据 保存数据 ##############################################################################  '''
'''
配合 *process.py 使用的函数处理
'''
def toCsv(from1, to2, funtionName):
    X = pd.read_csv(from1)
    X = funtionName(X)
    X = round(X, 2)
    X.to_csv(to2, index=False)
    print('toCsv 完毕................')

'''
对 windSpeed vs. rotateSpeed 的曲线拟合（实际没用上）
'''
def fitLineRegressCsv(from1, to2):
    X = pd.read_csv(from1)
    f1 = np.polyfit(X[Config.RotateSpeed], X[Config.WindSpeed], 1)  # 返回多项式系数
    func = np.poly1d(f1)  # 返回多项式表达式（多项式函数）
    WindSpeed_fit = func(X[Config.RotateSpeed])
    df2 = pd.DataFrame({Config.RotateSpeed: X[Config.RotateSpeed], Config.WindSpeed: WindSpeed_fit})
    df2[Config.WindSpeed] = round(df2[Config.WindSpeed], Config.scale_display)
    df2[Config.RotateSpeed] = round(df2[Config.RotateSpeed], Config.scale_display)
    df2.to_csv(to2, index=False)
    print('fitLineRegressCsv 完毕.................')

'''
对 rotateSpeed vs. windSpeed 的曲线拟合。
方法为： 曲线拟合之后求其反函数输出。即：将第一列作为x轴，第二列作为y轴，曲线拟合后，求反函数，再输出。
'''
def inverseCurveFitCsv(from1, to2, aveCp=''):
    X = pd.read_csv(from1)
    f1 = np.polyfit(X[Config.RotateSpeed], X[Config.WindSpeed], 1)  # 返回多项式系数
    func = np.poly1d(f1)  # 返回多项式表达式（多项式函数）
    # print("func:  ", func)
    invFunc = inversefunc(func)  # 反函数

    #生成windSpeed等间隔数据点,
    windSpeeds = np.arange(Config.windSpeedFilter_min, Config.windSpeedFilter_max, Config.scale_WindSpeed)
    # 得到windSpeeds 对应的rotateSpeeds
    RotateSpeeds_fit = invFunc(windSpeeds)

    # 过滤掉拟合后 rotateSpeed 不在[Config.RotateSpeedFiler_min, Config.rotateSpeedFilter_max] 范围内的点，并输出到 to2 文件
    df2 = pd.DataFrame({Config.WindSpeed: windSpeeds, Config.RotateSpeed: RotateSpeeds_fit})
    df2 = df2[ (df2[Config.RotateSpeed] >= Config.rotateSpeedFilter_min) & (df2[Config.RotateSpeed] <= Config.rotateSpeedFilter_max)]
    df2[Config.WindSpeed] = round(df2[Config.WindSpeed], Config.scale_display)
    df2[Config.RotateSpeed] = round(df2[Config.RotateSpeed], Config.scale_display)
    df2[Config.aveCp] = aveCp

    df2.to_csv(to2, index=False)
    print('fitLineRegressCsv 完毕.................')




''' 生成 Attr 文件 ################################################################################# '''
def toAttrCsv(from1, to2):
    X = pd.read_csv(from1)
    windSpeedMin = round(min(X[Config.WindSpeed]), Config.scale_display)
    windSpeedMax = round(max(X[Config.WindSpeed]), Config.scale_display)
    rotateSpeedMin = round(min(X[Config.RotateSpeed]), Config.scale_display)
    rotateSpeedMax = round(max(X[Config.RotateSpeed]), Config.scale_display)
    powerMin = round(min(X[Config.ActPower]), Config.scale_display)
    powerMax = round(max(X[Config.ActPower]), Config.scale_display)
    # attr = pd.DataFrame({'数据长度': [len(X)], '最小风速': [speedMin], '最大风速': [speedMax]})
    # attr = pd.DataFrame({'数据长度': [len(X)], '最小风速': [speedMin], '最大风速': [speedMax], '最小风向': [directionMin], '最大风向': [directionMax]})
    attr = pd.DataFrame(
        {'数据长度': [len(X)], '最小风速': [windSpeedMin], '最大风速': [windSpeedMax], '最小转速': [rotateSpeedMin], '最大转速': [rotateSpeedMax],
         '最小功率': [powerMin], '最大功率': [powerMax]})
    attr.to_csv(to2, index=False)
    print(from1+'----'+to2+'   toAttrCsv 完毕................')

def toLambdaAttrCsv(from1, to2):
    X = pd.read_csv(from1)
    windSpeedMin = round(min(X[Config.WindSpeed]), Config.scale_display)
    windSpeedMax = round(max(X[Config.WindSpeed]), Config.scale_display)
    rotateSpeedMin = round(min(X[Config.RotateSpeed]), Config.scale_display)
    rotateSpeedMax = round(max(X[Config.RotateSpeed]), Config.scale_display)
    attr = pd.DataFrame(
        {'数据长度': [len(X)], '最小风速': [windSpeedMin], '最大风速': [windSpeedMax], '最小转速': [rotateSpeedMin],
         '最大转速': [rotateSpeedMax]})
    attr.to_csv(to2, index=False)
    print(from1 + '----' + to2 + '   toAttrCsv 完毕................')

def toLineRegressCsv(from1, to2):
    X = pd.read_csv(from1)
    points_maxPower = pd.DataFrame(columns=[Config.WindSpeed, Config.RotateSpeed])  # WindSpeed切片->最高点 DataFrame
    WNAC_WindSpeed = X[Config.WindSpeed].drop_duplicates()
    for i in WNAC_WindSpeed:
        if i < 3.5:
            continue
        df = X[X[Config.WindSpeed] == i]  # X中，WindSpeed == i 切片的记录
        index_maxPower = df[Config.ActPower].nlargest(n=1).index[0]
        points_maxPower = points_maxPower.append(df.loc[index_maxPower, :])
    points_maxPower = points_maxPower[[Config.WindSpeed, Config.RotateSpeed]]
    points_maxPower[Config.WindSpeed] = round(points_maxPower[Config.WindSpeed], Config.scale_display)
    points_maxPower[Config.RotateSpeed] = round(points_maxPower[Config.RotateSpeed], Config.scale_display)
    points_maxPower.to_csv(to2, index=False)
    print('toLineRegressCsv 完毕...............')

def toLineRegressAttrCsv(from1, to2):
    X = pd.read_csv(from1)
    windSpeedMin = min(X[Config.WindSpeed])
    windSpeedMax = max(X[Config.WindSpeed])
    rotateSpeedMin = min(X[Config.RotateSpeed])
    rotateSpeedMax = max(X[Config.RotateSpeed])
    # attr = pd.DataFrame({'数据长度': [len(X)], '最小风速': [speedMin], '最大风速': [speedMax]})
    attr = pd.DataFrame({'数据长度': [len(X)], '最小风速': [windSpeedMin], '最大风速': [windSpeedMax], '最小转速': [rotateSpeedMin], '最大转速': [rotateSpeedMax]})
    attr.to_csv(to2, index=False)
    print('toAttrCsv 完毕................')



